<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="部门名称" prop="deptName">
            <el-input
               v-model="queryParams.deptName"
               placeholder="请输入部门名称"
               clearable
               style="width: 200px"
               @keyup.enter="handleQuery"
            />
         </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="部门状态" clearable style="width: 200px">
               <el-option
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
               />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd"
               v-hasPermi="['system:dept:add']"
            >新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="info"
               plain
               icon="Sort"
               @click="toggleExpandAll"
            >展开/折叠</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table
         v-if="refreshTable"
         v-loading="loading"
         :data="deptList"
         row-key="deptId"
         :default-expand-all="isExpandAll"
         :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
         <el-table-column prop="deptName" label="部门名称" width="260"></el-table-column>
         <el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
         <el-table-column prop="openHours" label="营业时间" width="150">
            <template #default="scope">
               <span v-if="scope.row.openHours">{{ scope.row.openHours }}</span>
               <span v-else style="color: #999;">未设置</span>
            </template>
         </el-table-column>
         <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
               <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
            </template>
         </el-table-column>
         <el-table-column label="创建时间" align="center" prop="createTime" width="200">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:dept:edit']">修改</el-button>
               <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:dept:add']">新增</el-button>
               <el-button v-if="scope.row.parentId != 0" link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:dept:remove']">删除</el-button>
               <el-button 
                  v-if="isLeafDeptInTable(scope.row)"
                  link 
                  type="warning" 
                  icon="Setting" 
                  @click="handleConfigFacility(scope.row)" 
                  v-hasPermi="['system:dept:edit']"
               >配置设施</el-button>
            </template>
         </el-table-column>
      </el-table>

      <!-- 添加或修改部门对话框 -->
      <el-dialog :title="title" v-model="open" width="700px" append-to-body>
         <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
            <el-row>
               <el-col :span="24" v-if="form.parentId !== 0">
                  <el-form-item label="上级部门" prop="parentId">
                     <el-tree-select
                        v-model="form.parentId"
                        :data="deptOptions"
                        :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                        value-key="deptId"
                        placeholder="选择上级部门"
                        check-strictly
                     />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="部门名称" prop="deptName">
                     <el-input v-model="form.deptName" placeholder="请输入部门名称" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="显示排序" prop="orderNum">
                     <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="负责人" prop="leader">
                     <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="联系电话" prop="phone">
                     <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="邮箱" prop="email">
                     <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
                  </el-form-item>
               </el-col>
               <!-- 营业时间 - 只对叶子节点显示 -->
               <el-col :span="12" v-if="isLeafDept">
                  <el-form-item label="营业时间" prop="openHours">
                     <div style="display: flex; align-items: center; gap: 8px;">
                        <el-time-picker
                           v-model="startTime"
                           placeholder="开始时间"
                           format="HH:mm"
                           value-format="HH:mm"
                           style="width: 120px;"
                           @change="updateOpenHours"
                        />
                        <span>-</span>
                        <el-time-picker
                           v-model="endTime"
                           placeholder="结束时间"
                           format="HH:mm"
                           value-format="HH:mm"
                           style="width: 120px;"
                           @change="updateOpenHours"
                        />
                     </div>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="部门状态">
                     <el-radio-group v-model="form.status">
                        <el-radio
                           v-for="dict in sys_normal_disable"
                           :key="dict.value"
                           :value="dict.value"
                        >{{ dict.label }}</el-radio>
                     </el-radio-group>
                  </el-form-item>
               </el-col>
            </el-row>
            
            <!-- 经纬度选择 - 只对叶子节点显示 -->
            <el-row v-if="isLeafDept">
               <el-col :span="24">
                  <el-form-item label="地理位置" prop="longitude">
                     <div class="location-section">
                        <div class="location-display" v-if="form.longitude && form.latitude">
                           <el-tag type="success" size="large">
                              经度: {{ form.longitude }}
                           </el-tag>
                           <el-tag type="success" size="large" style="margin-left: 8px;">
                              纬度: {{ form.latitude }}
                           </el-tag>
                           <el-button 
                              type="primary" 
                              size="small" 
                              @click="showLocationPicker = true"
                              style="margin-left: 12px;"
                           >
                              重新选择位置
                           </el-button>
                           <el-button 
                              size="small" 
                              @click="clearLocation"
                              style="margin-left: 8px;"
                           >
                              清除位置
                           </el-button>
                        </div>
                        <div v-else>
                           <el-button 
                              type="primary" 
                              @click="showLocationPicker = true"
                           >
                              选择地理位置
                           </el-button>
                           <span class="location-tip">为部门选择地理位置坐标</span>
                        </div>
                     </div>
                  </el-form-item>
               </el-col>
            </el-row>
            
            <!-- 环境图 - 只对叶子节点显示 -->
            <el-row v-if="isLeafDept">
               <el-col :span="24">
                  <el-form-item label="环境图">
                     <image-upload v-model="form.images" :limit="9" />
                  </el-form-item>
               </el-col>
            </el-row>
            
            <!-- 地址和描述字段 - 放在表单尾部 -->
            <el-row>
               <el-col :span="24">
                  <el-form-item label="地址" prop="address">
                     <el-input 
                        v-model="form.address" 
                        placeholder="请输入部门地址" 
                        maxlength="200"
                        show-word-limit
                     />
                  </el-form-item>
               </el-col>
            </el-row>
            
            <el-row>
               <el-col :span="24">
                  <el-form-item label="描述" prop="description">
                     <el-input 
                        v-model="form.description" 
                        type="textarea" 
                        placeholder="请输入部门描述" 
                        maxlength="500"
                        show-word-limit
                        :rows="4"
                     />
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>

      <!-- 地理位置选择弹窗 -->
      <el-dialog 
         title="选择部门地理位置" 
         v-model="showLocationPicker" 
         width="80%" 
         append-to-body
         :before-close="handleLocationPickerClose"
      >
         <div class="location-picker-content">
            <AmapPicker
               v-model="selectedLocation"
               :center="getMapCenter()"
               city="全国"
               height="500px"
               @change="handleLocationChange"
               @confirm="handleLocationConfirm"
               ref="amapPickerRef"
            />
         </div>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="showLocationPicker = false">取消</el-button>
               <el-button type="primary" @click="confirmLocationSelection">确认选择</el-button>
            </div>
         </template>
      </el-dialog>

      <!-- 配置设施对话框 -->
      <el-dialog :title="facilityTitle" v-model="facilityOpen" width="600px" append-to-body>
         <el-form
            ref="facilityRef"
            :model="facilityForm"
            label-width="120px"
         >
            <el-form-item label="钓场名称">
               <el-input v-model="currentDeptName" disabled />
            </el-form-item>
            <el-form-item label="选择设施" prop="facilityIds">
               <el-checkbox-group v-model="facilityForm.facilityIds">
                  <el-checkbox 
                     v-for="facility in facilityTypeList" 
                     :key="facility.id" 
                     :label="facility.id"
                     style="display: block; margin-bottom: 10px;"
                  >
                     {{ facility.name }}
                     <span v-if="facility.description" style="color: #999; font-size: 12px;">
                        （{{ facility.description }}）
                     </span>
                  </el-checkbox>
               </el-checkbox-group>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFacilityForm">确 定</el-button>
               <el-button @click="cancelFacility">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Dept">
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild, addDeptFacility, getDeptFacility } from "@/api/system/dept"
import { listFacilityType } from "@/api/pond/facilityType"
import AmapPicker from '@/components/AmapPicker/index.vue';

const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict("sys_normal_disable")

const deptList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const deptOptions = ref([])
const isExpandAll = ref(true)
const refreshTable = ref(true)

// 地理位置相关
const showLocationPicker = ref(false)
const selectedLocation = ref(null)
const amapPickerRef = ref(null)

// 营业时间相关
const startTime = ref('06:00')
const endTime = ref('23:00')

// 配置设施相关
const facilityOpen = ref(false)
const facilityTitle = ref("")
const currentDeptId = ref(null)
const currentDeptName = ref("")
const facilityTypeList = ref([])
const facilityForm = reactive({
  facilityIds: []
})

// 自定义地理位置验证函数
const validateLocation = (rule, value, callback) => {
  // 只有叶子部门需要验证地理位置
  if (isLeafDept.value) {
    if (!form.value.longitude || !form.value.latitude) {
      callback(new Error('地理位置不能为空'));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

// 自定义营业时间验证函数
const validateOpenHours = (rule, value, callback) => {
  // 只有叶子部门需要验证营业时间
  if (isLeafDept.value) {
    if (!value || value.trim() === '') {
      callback(new Error('营业时间不能为空'));
    } else if (!/^\d{2}:\d{2}-\d{2}:\d{2}$/.test(value)) {
      callback(new Error('营业时间格式不正确，应为 HH:mm-HH:mm'));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

const data = reactive({
  form: {},
  queryParams: {
    deptName: undefined,
    status: undefined
  },
  rules: {
    parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
    deptName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
    orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
    openHours: [{ validator: validateOpenHours, trigger: "change" }],
    longitude: [{ required: true,validator: validateLocation, trigger: "change" }],
    latitude: [{ required: true,validator: validateLocation, trigger: "change" }]
  },
})

// 计算属性：判断是否为叶子部门
const isLeafDept = computed(() => {
  // 新增时，如果选择的父部门没有子部门，则为叶子部门
  // 编辑时，如果当前部门没有子部门，则为叶子部门
  if (form.value.deptId) {
    // 编辑模式：检查当前部门是否有子部门
    const currentDept = findDeptInTree(deptList.value, form.value.deptId);
    return !currentDept || !currentDept.children || currentDept.children.length === 0;
  } else {
    // 新增模式：检查选择的父部门是否为叶子节点
    if (form.value.parentId) {
      const parentDept = findDeptInTree(deptList.value, form.value.parentId);
      return !parentDept || !parentDept.children || parentDept.children.length === 0;
    }
    return true; // 默认为叶子部门
  }
});

const { queryParams, form, rules } = toRefs(data)


/** 查询部门列表 */
function getList() {
  loading.value = true
  listDept(queryParams.value).then(response => {
    deptList.value = proxy.handleTree(response.data, "deptId")
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    deptId: undefined,
    parentId: undefined,
    deptName: undefined,
    orderNum: 0,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: "0",
    openHours: '06:00-23:00',
    images: "",
    longitude: undefined,
    latitude: undefined,
    address: undefined,
    description: undefined
  };
  
  // 设置营业时间默认值
  startTime.value = '06:00';
  endTime.value = '23:00';
  
  // 清理地理位置相关数据
  selectedLocation.value = null;
  showLocationPicker.value = false;
  
  // 如果地图选择器存在，也清理其状态
  if (amapPickerRef.value) {
    amapPickerRef.value.clearPosition();
  }
  
  proxy.resetForm("deptRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  
  // 确保清理地理位置状态
  selectedLocation.value = null;
  showLocationPicker.value = false;
  
  // 设置默认营业时间
  form.value.openHours = '06:00-23:00';
  
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId")
  })
  if (row != undefined) {
    form.value.parentId = row.deptId
  }
  open.value = true
  title.value = "添加部门"
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  listDeptExcludeChild(row.deptId).then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId")
  })
  getDept(row.deptId).then(response => {
    form.value = response.data
    
    // 解析营业时间数据
    if (response.data.openHours) {
      const times = response.data.openHours.split('-');
      if (times.length === 2) {
        startTime.value = times[0];
        endTime.value = times[1];
        form.value.openHours = response.data.openHours;
      }
    } else {
      // 如果没有营业时间，设置默认值
      startTime.value = '06:00';
      endTime.value = '23:00';
      form.value.openHours = '06:00-23:00';
    }
    
    // 处理图片数据格式转换
    if (response.data.images) {
      if (Array.isArray(response.data.images)) {
        // 如果后端返回的是对象数组格式，提取imageUrl转换为字符串格式供image-upload组件使用
        const imageUrls = response.data.images.map(img => {
          // 支持新格式 {imageUrl: "xxx"} 和旧格式 "xxx"
          return typeof img === 'object' && img.imageUrl ? img.imageUrl : img;
        }).filter(url => url); // 过滤掉空值
        form.value.images = imageUrls.join(',');
      } else if (typeof response.data.images !== 'string') {
        form.value.images = "";
      }
    } else {
      form.value.images = "";
    }
    
    // 清理之前的位置信息
    selectedLocation.value = null;
    
    // 如果有经纬度数据，设置选中位置。
    if (response.data.longitude && response.data.latitude) {
      selectedLocation.value = {
        lng: parseFloat(response.data.longitude),
        lat: parseFloat(response.data.latitude)
      };
    }
    
    open.value = true
    title.value = "修改部门"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate(valid => {
    if (valid) {
      // 准备提交数据，转换图片格式
      const submitData = { ...form.value };
      
      // 将图片字符串转换为后端需要的数组格式
      if (submitData.images && typeof submitData.images === 'string') {
        const imageUrls = submitData.images.split(',').filter(url => url.trim());
        submitData.images = imageUrls.map(url => ({ imageUrl: url.trim() }));
      } else if (!submitData.images) {
        submitData.images = [];
      }
      
      if (form.value.deptId != undefined) {
        updateDept(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDept(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?').then(function() {
    return delDept(row.deptId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 在部门树中查找指定部门 */
function findDeptInTree(tree, deptId) {
  for (let dept of tree) {
    if (dept.deptId === deptId) {
      return dept;
    }
    if (dept.children && dept.children.length > 0) {
      const found = findDeptInTree(dept.children, deptId);
      if (found) return found;
    }
  }
  return null;
}

/** 获取地图中心点 */
function getMapCenter() {
  if (selectedLocation.value) {
    return [selectedLocation.value.lng, selectedLocation.value.lat];
  }
  return [116.397428, 39.90923]; // 默认北京.
}

/** 处理位置变化 */
function handleLocationChange(data) {
  console.log('位置变化:', data);
}

/** 处理位置确认 */
function handleLocationConfirm(data) {
  console.log('位置确认:', data);
  selectedLocation.value = data.lngLat;
  
  // 更新表单数据
  form.value.longitude = data.lngLat.lng;
  form.value.latitude = data.lngLat.lat;
  
  proxy.$modal.msgSuccess('位置选择成功');
  showLocationPicker.value = false;
}

/** 确认位置选择 */
function confirmLocationSelection() {
  if (!selectedLocation.value) {
    proxy.$modal.msgWarning('请先选择一个位置');
    return;
  }
  
  // 更新表单数据
  form.value.longitude = selectedLocation.value.lng;
  form.value.latitude = selectedLocation.value.lat;
  
  proxy.$modal.msgSuccess('位置选择成功');
  showLocationPicker.value = false;
}

/** 清除位置 */
function clearLocation() {
  selectedLocation.value = null;
  form.value.longitude = undefined;
  form.value.latitude = undefined;
  proxy.$modal.msgInfo('已清除位置信息');
}

/** 更新营业时间 */
function updateOpenHours() {
  if (startTime.value && endTime.value) {
    form.value.openHours = `${startTime.value}-${endTime.value}`;
  } else {
    form.value.openHours = undefined;
  }
}

/** 处理位置选择器关闭 */
function handleLocationPickerClose() {
  showLocationPicker.value = false;
  
  // 如果没有选择位置就关闭，确保不保留之前的状态
  if (!form.value.longitude || !form.value.latitude) {
    selectedLocation.value = null;
  }
}

// 监听弹窗关闭，确保状态清理
watch(open, (newVal) => {
  if (!newVal) {
    // 弹窗关闭时，清理地理位置选择器状态
    showLocationPicker.value = false;
    
    // 如果当前表单没有保存的经纬度，清理selectedLocation
    if (!form.value.longitude || !form.value.latitude) {
      selectedLocation.value = null;
    }
  }
});

// 监听设施配置弹窗打开，获取已配置的设施
watch(() => facilityOpen.value, (newVal) => {
  if (newVal && currentDeptId.value) {
    getDeptFacility(currentDeptId.value).then((res) => {
      facilityForm.facilityIds = res.data.map((item) => {
        return item.facilityTypeId
      })
    }).catch(() => {
      facilityForm.facilityIds = []
    })
  }
})

/** 判断表格中的部门是否为叶子部门 */
function isLeafDeptInTable(dept) {
  return !dept.children || dept.children.length === 0;
}

/** 配置设施按钮操作 */
function handleConfigFacility(row) {
  currentDeptId.value = row.deptId;
  currentDeptName.value = row.deptName;
  facilityTitle.value = `配置设施 - ${row.deptName}`;
  
  // 获取设施类型列表
  listFacilityType({
    pageNum: 1,
    pageSize: 1000 // 获取所有设施类型
  }).then(response => {
    facilityTypeList.value = response.rows || [];
    facilityForm.facilityIds = []; // 清空已选择的设施
    facilityOpen.value = true;
  }).catch(error => {
    proxy.$modal.msgError("获取设施类型列表失败");
    console.error(error);
  });
}

/** 取消配置设施 */
function cancelFacility() {
  facilityOpen.value = false;
  facilityForm.facilityIds = [];
  currentDeptId.value = null;
  currentDeptName.value = "";
}

/** 提交配置设施 */
function submitFacilityForm() {
  if (facilityForm.facilityIds.length === 0) {
    proxy.$modal.msgWarning("请至少选择一个设施");
    return;
  }
  
  const params = {
    deptId: currentDeptId.value,
    facilityIds: facilityForm.facilityIds
  };
  
  addDeptFacility(params).then(() => {
    proxy.$modal.msgSuccess("配置设施成功");
    // 关闭弹窗
    cancelFacility();
  }).catch(error => {
    proxy.$modal.msgError("配置设施失败");
    console.error(error);
  });
}

getList()
</script>

<style scoped>
.location-section {
  width: 100%;
}

.location-display {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.location-tip {
  margin-left: 12px;
  color: #909399;
  font-size: 13px;
}

.location-picker-content {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .location-display {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .location-display .el-button {
    margin-left: 0 !important;
    margin-top: 8px;
  }
}
</style>
